﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DingTalk.Api;
using DingTalk.Api.Request;
using DingTalk.Api.Response;
using FastJSON;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using DingTida.Models;
using RouteAttribute = Microsoft.AspNetCore.Components.RouteAttribute;
using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Data.SqlClient;
using Microsoft.IdentityModel.Protocols;
using System.Data;
using System.IO;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Hosting.Internal;
using Microsoft.AspNetCore.Hosting;
using System.Globalization;
using DingTida.BLL;
using DingTida.IBLL;
using DingTida.Comnon;

namespace DingTida.Controllers
{
    [Route("api/[controller]")]
   // [ApiController]
    public class LeaveController : ControllerBase
    {
        public string access_token = "";
        public EasyStarContext db;
        public OapiUserGetuserinfoResponse rsp = null;
        public string name;
        public IMemoryCache Cache;
        private IWebHostEnvironment _webHostEnvironment;
        public IWorkFlowInstance wfi;
        public IMsg msg;
        public LeaveController(EasyStarContext _db, IMemoryCache _cache, IWebHostEnvironment webHostEnvironment, IWorkFlowInstance _wfi, IMsg _msg)
        {
            this.db = _db;
            this.Cache = _cache;
            this._webHostEnvironment = webHostEnvironment;
            this.wfi = _wfi;
            this.msg = _msg;
        }


        [HttpPost]
        public IActionResult apply(string begin, string end, string hour, string day, string year, string typ, string empid,string reason,int idd)
        {

            DateTime dtb = DateTime.ParseExact(begin, "yyyyMMddHHmm", System.Globalization.CultureInfo.CurrentCulture);
            DateTime dte = DateTime.ParseExact(end, "yyyyMMddHHmm", System.Globalization.CultureInfo.CurrentCulture);
            int hr = int.Parse(hour);
            int dy = int.Parse(day);
            int yr = int.Parse(year);


            var off = db.WorkFlows.Any(c => c.Begindate == dtb && c.Enddate == dte && c.Staffid == empid);
            if (off)
            {
                return Ok(new { msg = "同样的申请已经存在了" });
            }
            //ls:['请选择类型', '出差', '事假', '病假', '年休假', '丧假', '产假', '陪产假', '婚假', '调休假', '看护假', '工伤假',],
            else if (typ == "" || typ == null)
            {
                return Ok(new { msg = "请选择正确的请假或出差类型" });

            }
            else if (typ == "出差" || typ == "事假" || typ == "病假" || typ == "丧假" || typ == "产假" || typ == "婚假" || typ == "看护假" || typ == "工伤假")
            {
                var oh = db.KmQqDj.Any(c => c.QqTime0 == dtb && c.QqTime1 == dte && c.EmpId == int.Parse(empid));
                if (oh)
                {
                    return Ok(new { msg = "同样的申请已经存在了" });

                }
                else
                {

                    flowbegin(dtb,dte,hr,dy,reason,typ,empid);
                    return Ok(new { msg="申请成功，请留意我的申请"});

                }

            }
            else if (typ == "年休假")
            {
                var em = db.EmEmpData.Where(c => c.EmpNo == empid).FirstOrDefault();
                var nj = db.KmNianJia.Where(c => c.NYear == yr&&c.EmpId==em.EmpId).FirstOrDefault();
                var os = nj.ICount - nj.IUseCalc;
                if (os == 0)
                {
                    return Ok(new { msg = year + "年度年假已经休完" });

                }
                else if (os > 0)
                {

                    if (os - dy >= 0)
                    {
                        flowbegin(dtb, dte, hr, dy, reason, typ, empid);
                        return Ok(new { msg = "申请成功，请留意我的申请" });
                    }
                    else {
                        return Ok(new { msg = year + "年度可用年假低于申请天数" });

                    }


                }
                else {

                    return Ok(new { msg = year + "年假故障 请联系程序员" });
                }


            }
            else if (typ == "调休假")
            {
                flowbegin(dtb, dte, hr, dy, reason, typ, empid,idd);
                return Ok(new { msg = "申请成功，请留意我的申请" });

            }
            else
            {

                return Ok(new { msg = "未正确选择类型" });
            }

           // return Ok(new { msg = "申请成功" });
        }


        public void flowbegin(DateTime begin, DateTime end, int hour, int day, string reason, string type, string empid)
        {
            var emp = db.EmEmpData.Where(c => c.EmpNo == empid).FirstOrDefault();
            var dept = db.EsDept.Where(c => c.FullCode == emp.Dept).FirstOrDefault();
            var IsExit = db.WorkFlows.Any(c => c.Staffid == empid && c.FlowContent == reason);

            WorkFlows wf = new WorkFlows();
            string id = Guid.NewGuid().ToString();
            wf.Staffid = empid;
            wf.Hour = hour;
            wf.Day = hour / 8;
            wf.Begindate = begin;
            wf.Enddate = end;

            wf.IsComplete = false;
            wf.FlowContent = emp.Fname + empid + "申请" + type + "由" + begin.ToString("yyyyMMddHHmm") + "到" + end.ToString("yyyyMMddHHmm") + "共" + day.ToString() + "天" + "折合" + hour.ToString() + "小时";
            wf.States = "发起";
            wf.Type = type;
            wf.Reason = reason;
            wf.Applydate = System.DateTime.Now;
            wf.FlowId = id;
            var u1 = db.CustomDictionary.Where(c => c.Ckey == "leave1").FirstOrDefault();
            var u2 = db.CustomDictionary.Where(c => c.Ckey == "leave2").FirstOrDefault();
            db.WorkFlows.Add(wf);
            db.SaveChanges();
            #region 判断是否为经理级别，不是直接部门审核

            if (emp.CardNo2 == "" || emp.CardNo2 == null)//如果不是经理级别
            {
                var nid = wfi.AddInstanceByManager(empid, id);// 添加流转步骤一  转经理审批
                                                              //msg.SendMsg("钉钉提示您，泰德小程序内OA项目 有一项待您核签，", staffid);
            }
            #endregion
            #region 如果是经理直接由蒲总审核
            else
            {

                wfi.AddInstanceByUser(1, emp.CardNo2, id);

            } 
            #endregion
            #region 大于3天 彭沅沅审核完  到汤建松审 
            if (day >= 3)
            {

                wfi.AddInstanceByUser(2, u1.Value, id);
                wfi.AddInstanceByUserLast(3, u2.Value, id);

            }
            #endregion
            #region 小于3天 直接由彭沅沅审核完
            else
            {
                wfi.AddInstanceByUserLast(2, u2.Value, id);


            }
            #endregion



        }


        public void flowbegin(DateTime begin, DateTime end, int hour, int day, string reason, string type, string empid,int idd)
        {
            var emp = db.EmEmpData.Where(c => c.EmpNo == empid).FirstOrDefault();
            var dept = db.EsDept.Where(c => c.FullCode == emp.Dept).FirstOrDefault();
            var IsExit = db.WorkFlows.Any(c => c.Staffid == empid && c.FlowContent == reason);

            WorkFlows wf = new WorkFlows();
            string id = Guid.NewGuid().ToString();
            wf.Staffid = empid;
            wf.Hour = hour;
            wf.Day = hour / 8;
            wf.Begindate = begin;
            wf.Enddate = end;
            wf.Reason = reason;
            wf.Applydate = System.DateTime.Now;
            wf.IsComplete = false;
            wf.FlowContent = emp.Fname + empid + "申请" + type + "由" + begin.ToString("yyyyMMddHHmm") + "到" + end.ToString("yyyyMMddHHmm") + "共" + day.ToString() + "天" + "折合" + hour.ToString() + "小时";
            wf.States = "发起";
            wf.Type = type;
            wf.FlowId = id;
            wf.OtherId = idd;

            var bwf = db.WorkFlows.Where(c => c.Id == idd).FirstOrDefault();
            bwf.IsAdjust = true;

            var u1 = db.CustomDictionary.Where(c => c.Ckey == "leave1").FirstOrDefault();
            var u2 = db.CustomDictionary.Where(c => c.Ckey == "leave2").FirstOrDefault();
            db.WorkFlows.Add(wf);
            db.SaveChanges();
            #region 判断是否为经理级别，不是直接部门审核

            if (emp.CardNo2 == "" || emp.CardNo2 == null)//如果不是经理级别
            {
                var nid = wfi.AddInstanceByManager(empid, id);// 添加流转步骤一  转经理审批
                                                              //msg.SendMsg("钉钉提示您，泰德小程序内OA项目 有一项待您核签，", staffid);
            }
            #endregion
            #region 如果是经理直接由蒲总审核
            else
            {

                wfi.AddInstanceByUser(1, emp.CardNo2, id);

            }
            #endregion
            #region 大于3天 彭沅沅审核完  到汤建松审 
            if (day >= 3)
            {

                wfi.AddInstanceByUser(2, u1.Value, id);
                wfi.AddInstanceByUserLast(3, u2.Value, id);

            }
            #endregion
            #region 小于3天 直接由彭沅沅审核完
            else
            {
                wfi.AddInstanceByUserLast(2, u2.Value, id);


            }
            #endregion



        }

        public IActionResult saltype(string staffid)
        {

            var salarytype = db.EmEmpData.Where(c => c.EmpNo == staffid).FirstOrDefault().Jxfs;

          return  Ok(new { jxfs = salarytype });
            
        
        
        }

        [HttpPost]

        public IActionResult imgbeginsendcar(string type,int id)
        {


          //  var f = Request.Form.Files["img"];

       
            var uploadfile = Request.Form.Files["img"];//Request.Form.Files[0];
            var now = DateTime.Now;
            var webRootPath = Directory.GetCurrentDirectory();


            var filePath = string.Format("/wwwroot/images/{0}/{1}/{2}/", now.ToString("yyyy"), now.ToString("yyyyMM"), now.ToString("yyyyMMdd"));
            var filePath1 = string.Format("/images/{0}/{1}/{2}/", now.ToString("yyyy"), now.ToString("yyyyMM"), now.ToString("yyyyMMdd"));

            if (!Directory.Exists(webRootPath + filePath))
            {
                Directory.CreateDirectory(webRootPath + filePath);
            }

            if (uploadfile != null)
            {
                var fileExtension = Path.GetExtension(uploadfile.FileName);

                //判断后缀是否是图片
                const string fileFilt = ".gif|.jpg|.php|.jsp|.jpeg|.png|.";
                if (fileExtension == null)
                {
                    return Ok(new {msg="图片没有后缀" });
                }
                if (fileFilt.IndexOf(fileExtension.ToLower(), StringComparison.Ordinal) <= -1)
                {
                    return Ok(new { msg = "文件不是图片" });
                }

                //判断文件大小    
                long length = uploadfile.Length;
                if (length > 1024 * 1024 * 6) //2M
                {
                    return Ok(new { msg = "图片不能超过6M" });
                }

                var strDateTime = DateTime.Now.ToString("yyMMddhhmmssfff"); //取得时间字符串
                var strRan = Convert.ToString(new Random().Next(100, 999)); //生成三位随机数
                var saveName = strDateTime + strRan + fileExtension;
                var CarSend = db.AppCarSendInfo.Where(c => c.Id == id).FirstOrDefault();

                if (type == "begin")
                {
                    CarSend.Beginkm = filePath1 + saveName;


                }
                else
                {

                    CarSend.Endkm = filePath1 + saveName;
                }
                db.SaveChanges();
                using (FileStream fs = System.IO.File.Create(webRootPath + filePath + saveName))
                {
                    uploadfile.CopyTo(fs);
                    fs.Flush();
                }

                return Ok(new { msg = "上传成功" });
            }
            return Ok(new { msg= "上传失败" });
        }

       



        [HttpPost]
        public IActionResult SendCar(bool IsSelfCar, string destination,string original,string dtime,string moblie, string remark,string usersnumber,string empid)
        {

            var dstime = DateTime.ParseExact(dtime, "yyyyMMddHHmm", System.Globalization.CultureInfo.CurrentCulture);
            AppCarSendInfo ifo = new AppCarSendInfo();
            ifo.Departure = original;
            ifo.Destination = destination;
            ifo.NeedDateTime = dstime;
            ifo.TelNo = moblie;
            ifo.Remark = remark;
            ifo.Usersnumber = usersnumber;
            ifo.StaffInUser = empid;
            ifo.IsSelfCar = IsSelfCar;








            var emp = db.EmEmpData.Where(c => c.EmpNo == empid).FirstOrDefault();
            var dept = db.EsDept.Where(c => c.FullCode == emp.Dept).FirstOrDefault();
            var IsExit = db.WorkFlows.Any(c => c.Staffid == empid && c.FlowContent == remark);

            WorkFlows wf = new WorkFlows();
            string id = Guid.NewGuid().ToString();
            wf.Staffid = empid;
            wf.Reason = remark;
         
            wf.Begindate = dstime;
            wf.Enddate = dstime;

            wf.IsComplete = false;

            if (IsSelfCar)
            {

                wf.FlowContent = "私人自驾" + emp.Fname + empid + "申请" + "派车" + "于" + dstime.ToString("yyyyMMddHHmm") + "从" + original + "到" + destination + "申请人号码" + moblie;

            }
            else
            {
                wf.FlowContent = "公司派车"+emp.Fname + empid + "申请" + "派车" + "于" + dstime.ToString("yyyyMMddHHmm") + "从" + original + "到" + destination + "申请人号码" + moblie;

            }
            wf.States = "发起";
            wf.Type = "派车";
            wf.FlowId = id;
            wf.Applydate = System.DateTime.Now;
            
            var u2 = db.CustomDictionary.Where(c => c.Ckey == "car").FirstOrDefault();
            db.WorkFlows.Add(wf);
            ifo.Other = id;

            db.AppCarSendInfo.Add(ifo);
            db.SaveChanges();
            #region 判断是否为经理级别，不是直接部门审核

            if (emp.CardNo2 == "" || emp.CardNo2 == null)//如果不是经理级别
            {
                var nid = wfi.AddInstanceByManager(empid, id);// 添加流转步骤一  转经理审批
                                                              //msg.SendMsg("钉钉提示您，泰德小程序内OA项目 有一项待您核签，", staffid);
            }
            #endregion
            #region 如果是经理直接由蒲总审核
            else
            {

                wfi.AddInstanceByUser(1, emp.CardNo2, id);

            }
            #endregion
            #region 派车 汤建松审 核
          
            
                wfi.AddInstanceByUserLast(2, u2.Value, id);
            
            #endregion

            return Ok(new { msg = "申请成功" });

        }
        [HttpGet]
        public IActionResult GetCarSendInfo(string UserId)
        {
            var lst = db.AppCarSendInfo.Where(c => c.StaffInUser == UserId&&c.Beginkm==null&&c.Endkm==null).ToList();
            return Ok(lst);
        }


        public  double gethour(DateTime dt1, DateTime dt2)
        {
            

            TimeSpan ts = dt1.Subtract(dt2);

            double hours = ts.TotalHours;//24

            return hours;

        }

        public IActionResult adjust(string staffid)
        {

            var jxfs = db.EmEmpData.Where(c => c.EmpNo == staffid).FirstOrDefault();
            if (jxfs.Jxfs != "月薪")
            {

                return Ok(new { msg = "只有月薪的同事可以选择调休" });

            }
            else
            {



                var wf = db.WorkFlows.Where(c => c.Staffid == jxfs.EmpNo && c.States == "完成" && c.Type == "加班" && c.IsAdjust != true).Select(c => new { id = c.Id,
                    begin = c.Begindate,
                    end = c.Enddate,
                 

                }).ToList();

                List<dts> li = new List<dts>();
                foreach (var im in wf)
                {
                    dts ds = new dts();
                    ds.begin = (DateTime)im.begin;
                    ds.end = (DateTime)im.end;
                    ds.hours= gethour((DateTime)im.end, (DateTime)im.begin);
                    ds.id = im.id;
                    li.Add(ds);

                }

               



                return Ok(new { msg = "可正常调休", data = li });

            }



        }

        public IActionResult GetCarSendList(string staffid)
        {

            var ls = db.AppCarSendInfo.Where(c=>c.StaffInUser==staffid).ToList();
            var lss = ls.Where(c => c.BeginImg == null || c.EndImg == null).ToList();


            return Ok(lss);




        }

        [HttpPost]
        public IActionResult arra(int flowId, int carId)
        {
            var flowInst = db.WorkFlowsInstance.Where(c => c.Id == flowId).FirstOrDefault();
            var carflow = db.WorkFlows.Where(c => c.FlowId == flowInst.WorkFlowId).FirstOrDefault();
            var car = db.AppCar.Where(c => c.Id == carId).FirstOrDefault();
            var carsendflow = db.AppCarSendInfo.Where(c => c.Other == flowInst.WorkFlowId).FirstOrDefault();
            var flowlist = db.WorkFlowsInstance.Where(c => c.WorkFlowId == carflow.FlowId).ToList();

            foreach (var a in flowlist)
            {
                a.IsCurrentStep = false;
            
            }



            carsendflow.CarId = car.Id;
            carflow.FlowContent += "车辆信息：" + "品牌：" + car.Barnd + "名称：" + car.Name + "车牌号码:" + car.CarNo + "司机联系方式" + car.DriverUser + car.DriverTelNo;
            carflow.States = "完成";
            
            var wf = carflow;
            db.SaveChanges();

            msg.SendMsg("您的申请已经被通过" + wf.FlowContent, wf.Staffid);




            return Ok(new { msg = "派车成功" });


        }

        //public IActionResult arra(string flowId, int  carId)
        //{

        //    var car = db.AppCar.Where(c => c.Id == carId).FirstOrDefault();
        //    var flow = db.WorkFlows.Where(c => c.FlowId == flowId).FirstOrDefault();
        //    flow.FlowContent += "司机";


        
        
        //}


    }


    public class dts { 

     
    public int  id { get; set; }
    public DateTime begin { get; set; }
    public DateTime end { get; set; }

    public double hours { get; set; }
    
    }
}